package com.ruoyi.performance.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.performance.domain.AssessmentItems;
import com.ruoyi.performance.domain.AssessmentResult;
import com.ruoyi.performance.domain.PerformanceTemplate;
import com.ruoyi.performance.mapper.AssessmentItemsMapper;
import com.ruoyi.performance.mapper.AssessmentResultMapper;
import com.ruoyi.performance.mapper.PerformanceTemplateMapper;
import com.ruoyi.performance.mapper.ScoringMapper;
import com.ruoyi.performance.service.IScoringService;
import com.ruoyi.teacher.domain.Teacher;
import com.ruoyi.teacher.mapper.TeacherMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.performance.mapper.ScoringMapper;
import com.ruoyi.performance.domain.Scoring;
import com.ruoyi.performance.service.IScoringService;

/**
 * 教师考核打分Service业务层处理
 *
 * @author eden
 * @date 2023-05-20
 */

@Service
@Slf4j
public class ScoringServiceImpl implements IScoringService {
    @Autowired
    private ScoringMapper scoringMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private PerformanceTemplateMapper templateMapper;
    @Autowired
    private AssessmentItemsMapper itemsMapper;
    @Autowired
    private AssessmentResultMapper resultMapper;

    /**
     * 查询教师考核打分
     *
     * @param Id 教师考核打分主键
     * @return 教师考核打分
     */
    @Override
    public Scoring selectScoringById(Long Id) {
        return scoringMapper.selectScoringById(Id);
    }

    /**
     * 查询教师考核打分列表
     *
     * @param scoring 教师考核打分
     * @return 教师考核打分
     */
    @Override
    public List<Scoring> selectScoringList(Scoring scoring) {
        return scoringMapper.selectScoringList(scoring);
    }

    /**
     * 新增教师考核打分
     *
     * @param scoring 教师考核打分
     * @return 结果
     */
    @Override
    public int insertScoring(Scoring scoring) {
        return scoringMapper.insertScoring(scoring);
    }

    /**
     * 修改教师考核打分
     *
     * @param scoring 教师考核打分
     * @return 结果
     */
    @Override
    public int updateScoring(Scoring scoring) {
        return scoringMapper.updateScoring(scoring);
    }

    /**
     * 批量删除教师考核打分
     *
     * @param Ids 需要删除的教师考核打分主键
     * @return 结果
     */
    @Override
    public int deleteScoringByIds(Long[] Ids) {
        return scoringMapper.deleteScoringByIds(Ids);
    }

    /**
     * 删除教师考核打分信息
     *
     * @param Id 教师考核打分主键
     * @return 结果
     */
    @Override
    public int deleteScoringById(Long Id) {
        return scoringMapper.deleteScoringById(Id);
    }

    @Override
    public void listSealf() {
        Scoring scoring = new Scoring();
        // 获取登录id
        Long userId = SecurityUtils.getUserId();
        // 假数据
        userId = 109l;
        Teacher teacher = teacherMapper.findByUserId(userId);
        Integer type = teacher.getType();
        if (type != null) {
            PerformanceTemplate performanceTemplate = templateMapper.selectPerformanceTemplateById(Long.valueOf(type));
            String str = performanceTemplate.getAssesProject();
            String[] split = str.split(",");
            for (String s : split) {
                AssessmentItems items = itemsMapper.findByItemName(s);
                scoring.setAssessmentName(items.getItemName());
                scoring.setTarget(items.getTargetValue());
                scoring.setWeight(Math.toIntExact(items.getWeight()));
                scoring.setTeacherName(SecurityUtils.getUsername());
                scoring.setAssessmentMonth(new Date());
                scoring.setState(0);
                scoringMapper.insertScoring(scoring);

            }
        }


    }

    /**
     * public static void main(String[] args) throws Exception {
     * <p>
     * String botUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=**********";
     * WeChatBotUtils weChatBot = new WeChatBotUtils(botUrl, true);
     * <p>
     * // 发送文本消息
     * weChatBot.sendTextMsg("测试消息\n" + "hello world!");
     * <p>
     * // 发送图片消息
     * weChatBot.sendImgMsg("C:/User/Desktop/test.jpg");
     * <p>
     * // 发送MarkDown消息
     * String markdownMsg =
     * "测试：您的会议室已经预定，稍后会同步到`邮箱` \n" +
     * "    >**事项详情** \n" +
     * "    >事　项：<font color=\"info\">开会</font> \n" +
     * "    >组织者：@admin \n" +
     * "    >参与者：@admin \n" +
     * "    >\n" +
     * "    >会议室：<font color=\"info\">广州TIT 1楼 301</font>\n" +
     * "    >日　期：<font color=\"warning\">2022年4月22日</font>\n" +
     * "    >时　间：<font color=\"comment\">上午9:00-11:00</font>\n" +
     * "    >\n" +
     * "    >请准时参加会议。\n";
     * weChatBot.sendMarKDownMsg(markdownMsg);
     * <p>
     * // 发送文件消息
     * weChatBot.sendFileMsg("C:/User/Desktop/test.xlsx");
     * <p>
     * }
     *
     * @param scoringlist
     * @return
     */
    @Override
    public int oneSelf(List<Scoring> scoringlist) {

        Long userId = SecurityUtils.getUserId();
        userId = 109l;
        String name = teacherMapper.findByUserId(userId).getName();
        for (Scoring scoring : scoringlist) {
            scoring.setState(1);
            scoringMapper.updateScoring(scoring);
        }

        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=789b22e2-415c-4dab-b9c8-c51277a8b692");
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
//构建一个json格式字符串textMsg，其内容是接收方需要的参数和消息内容
//        String textMsg = "{\"msgtype\":\"text\",\"text\":{\"content\":\"你好\"},\"at\":{\"atMobiles\":[\"xxx\"],\"isAtAll\":false}}";
        String textMsg = "{\"msgtype\":\"text\"," +
                "\"text\":{\"content\":\"你好,@"+name+" 先生/女生:有绩效待审核,点击到达;http://172.16.7.214/performance/scoring\"}," +
                "\"at\":{\"atMobiles\":[\"xxx\"]," +
                "\"isAtAll\":false}}";
        StringEntity se = new StringEntity(textMsg, "utf-8");
        httppost.setEntity(se);
        try {
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(result);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//        EnterpriseWeChatRobot.sendMan(name);
//        String botUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=789b22e2-415c-4dab-b9c8-c51277a8b692";
//        WeChatBotUtils weChatBot = new WeChatBotUtils(botUrl, false);
//        try {
//            weChatBot.sendTextMsg("sdfwedfgregaeger");
//        } catch (Exception e) {
//
//            throw  new  RuntimeException("发送企业微信消息失败",  e);
//        }


        return 1;
    }

    @Override
    public int other(List<Scoring> scoringlist) {
        Integer ii = 0;
        int i = 0;

        for (Scoring scoring : scoringlist) {
            ii = ((scoring.getAssessmentScore()) * (scoring.getWeight())) / 100;
//            i = i +ii;
            scoring.setState(2);
            scoring.setAssessmentManName(SecurityUtils.getUsername());
            scoringMapper.updateScoring(scoring);

            System.out.println(ii + "-------------ddd------------------");
            i += ii;

        }
            System.out.println(i + "-----------wwi--------------------");

        Long userId = SecurityUtils.getUserId();
        userId = 109l;
        String name = teacherMapper.findByUserId(userId).getName();

        AssessmentResult result = new AssessmentResult();
        result.setCreateTime(new Date());
        result.setTeacherId(name);
        result.setAssessmentScore(Long.valueOf(i));
        result.setAssessmentManId(name);

        resultMapper.insertAssessmentResult(result);


        return 1;
    }


}
